#include "TConfig.h"

#include "Tools.h"
#include <QSettings>
#include <QBitArray>
#include <QApplication>

const unsigned char* const RC4_KEY = (const unsigned char*) "lee.TCClient";
const int RC4_KEYLEN = 12;

TConfig* TConfig::_instance = 0;

TConfig::TConfig() :
    _serverUrl(""),
    _logPath("./logs/"),
    _incomingDir("./incoming/"),
    _isScreenshotMinisize(true),
    _tmpDir("./tmp/")
{
    QSettings settings("./server.cfg", QSettings::IniFormat);

    //ServerUrl
    if(settings.contains("ServerUrl"))
        _serverUrl = settings.value("ServerUrl").toString();

    //user & password
    if(settings.contains("user"))
        _lastUser = Tools::crypt(settings.value("user").toByteArray(), RC4_KEY, RC4_KEYLEN);
    if(settings.contains("pwd"))
        _lastPwd = Tools::crypt(settings.value("pwd").toByteArray(), RC4_KEY, RC4_KEYLEN);

    if(settings.contains("isScreenshotMinisize"))
        _isScreenshotMinisize = settings.value("isScreenshotMinisize").toBool();
}

TConfig* TConfig::instance()
{
    if (!_instance)
        _instance = new TConfig();
    return _instance;
}

QString TConfig::version()
{
    return "0.5.0";
}

const QRect& TConfig::desktopWindowRect() const
{
    return _desktopWindowRect;
}

QString TConfig::serverUrl()
{
    return _serverUrl;
}

QString TConfig::logPath()
{
    return _logPath;
}

QString TConfig::lastUser()
{
    return _lastUser;
}

QString TConfig::lastPwd()
{
    return _lastPwd;
}

void TConfig::saveDesktopWindowRect(const QRect& rect)
{
    _desktopWindowRect = rect;
}

void TConfig::saveUser(const QString &user, const QString &pwd)
{
    _lastUser = user;
    _lastPwd = pwd;
}

void TConfig::save()
{
    QSettings settings("./server.cfg", QSettings::IniFormat);
    QString value;

    // DesktopWindowRect
    value.sprintf("%d,%d,%d,%d", _desktopWindowRect.left(), _desktopWindowRect.top(), _desktopWindowRect.width(), _desktopWindowRect.height());
    settings.setValue("DesktopWindowRect", value);

    //user & password
    settings.setValue("user", Tools::crypt(_lastUser.toUtf8(), RC4_KEY, RC4_KEYLEN));
    settings.setValue("pwd", Tools::crypt(_lastPwd.toUtf8(), RC4_KEY, RC4_KEYLEN));

    settings.setValue("isScreenshotMinisize", _isScreenshotMinisize);
}

QString TConfig::incomingDir()
{
   return QApplication::applicationDirPath() +  _incomingDir;

   // return "C:\\Users\\minhua\\tc_incoming";
}

QString TConfig::tmpDir()
{
    return _tmpDir;
}

bool TConfig::isScreenshotMinisize()
{
    return this->_isScreenshotMinisize;
}

void TConfig::setIsScreenshotMinisize(bool is)
{
    this->_isScreenshotMinisize = is;
}
